import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';

// import 'package:camera_with_rtmp/camera.dart';

// import 'package:flutter_rtmp_publisher/flutter_rtmp_publisher.dart';

import 'package:path_provider/path_provider.dart';
import 'package:rtmp_publisher/camera.dart';
import 'package:video_player/video_player.dart';

class CameraApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    return MaterialApp(
      home: CameraExampleHome(),
    );
  }
}

List<CameraDescription> cameras = [];

Future<void> main() async {
  // Fetch the available cameras before initializing the app.
  try {
    WidgetsFlutterBinding.ensureInitialized();
    cameras = await availableCameras();
  } on CameraException catch (e) {
    // logError(e.code, e.description);
  }
  runApp(CameraApp());
}


class CameraExampleHome extends StatefulWidget {
  @override
  _CameraAppState createState() => _CameraAppState();
}

class _CameraAppState extends State<CameraExampleHome> {

  CameraController controller;

  VideoPlayerController videoController;



  void initCamers()async{


    controller = CameraController(cameras[1], ResolutionPreset.medium,enableAudio: true,androidUseOpenGL: true);

    try {
      await controller.initialize();

    } on CameraException catch (e) {
      // _showCameraException(e);
    }

    if (mounted) {
      setState(() {});
    }
  }

  @override
  void initState() {
    super.initState();

    initCamers();


  }
  Timer _timer;

  Future<String> startVideoStreaming() async {

    if (!controller.value.isInitialized) {
      // showInSnackBar('Error: select a camera first.');
      return null;
    }

    if (controller.value.isStreamingVideoRtmp) {
      return null;
    }

    // Open up a dialog for the url
    String myUrl = 'rtmp://192.168.0.101:1935/live/Yry01AuHiK7FDcCc35S4IzoOjgm2v8KyBpNlS52DyhMEXiJe';

    try {
      if (_timer != null) {
        _timer.cancel();
        _timer = null;
      }
      // url = myUrl;
      await controller.startVideoStreaming(myUrl);
      _timer = Timer.periodic(Duration(seconds: 1), (timer) async {
        var stats = await controller.getStreamStatistics();
        // print(stats);
      });
    } on CameraException catch (e) {
      // _showCameraException(e);
      return null;
    }
    return myUrl;
  }

  Future<void> stopVideoStreaming() async {
    if (!controller.value.isStreamingVideoRtmp) {
      return null;
    }

    try {
      await controller.stopVideoStreaming();
      // if (_timer != null) {
      //   _timer.cancel();
      //   _timer = null;
      // }
    } on CameraException catch (e) {
      // _showCameraException(e);
      return null;
    }
  }



  @override
  void dispose() {
    controller?.dispose();
    super.dispose();
  }
  String timestamp() => DateTime.now().millisecondsSinceEpoch.toString();


  Future<String> takePicture() async {
    if (!controller.value.isInitialized) {
      return null;
    }
    final Directory extDir = await getExternalStorageDirectory();
    final String dirPath = '${extDir.path}/Pictures/flutter_test';
    await Directory(dirPath).create(recursive: true);
    final String filePath = '$dirPath/${timestamp()}.jpg';

    if (controller.value.isTakingPicture) {
      // A capture is already pending, do nothing.
      return null;
    }

    try {
      await controller.takePicture(filePath);
    } on CameraException catch (e) {
      return null;
    }
    return filePath;
  }

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Camera example'),
      ),
      body: Column(
        children: <Widget>[
          Expanded(
            child: Container(
              child: Padding(
                padding: const EdgeInsets.all(1.0),
                child: Center(
                  child: _cameraPreviewWidget(),
                ),
              ),
              decoration: BoxDecoration(
                color: Colors.black,
                border: Border.all(
                  color: controller != null && controller.value.isRecordingVideo
                      ? controller.value.isStreamingVideoRtmp
                      ? Colors.redAccent
                      : Colors.orangeAccent
                      : controller != null &&
                      controller.value.isStreamingVideoRtmp
                      ? Colors.blueAccent
                      : Colors.grey,
                  width: 3.0,
                ),
              ),
            ),
          ),

          Padding(
            padding: const EdgeInsets.all(5.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[

                RaisedButton(onPressed: (){
                  print('11');

                  takePicture().then((String filePath) {
                    if (mounted) {
                      setState(() {

                        videoController?.dispose();
                        videoController = null;
                      });
                      // if (filePath != null) showInSnackBar('Picture saved to $filePath');
                    }
                  });

                  // startVideoStreaming().then((String url) {
                  //   if (mounted) setState(() {});
                  //   if (url != null) print('Streaming video to $url');
                  //   // Wakelock.enable();
                  // });




                  // controller.startVideoStreaming('rtmp://192.168.0.101:1935/live/Yry01AuHiK7FDcCc35S4IzoOjgm2v8KyBpNlS52DyhMEXiJe');
                })
                
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _cameraPreviewWidget() {
    if (controller == null || !controller.value.isInitialized) {
      return const Text(
        'Tap a camera',
        style: TextStyle(
          color: Colors.white,
          fontSize: 24.0,
          fontWeight: FontWeight.w900,
        ),
      );
    } else {
      return AspectRatio(
        aspectRatio: controller.value.aspectRatio,
        child: CameraPreview(controller),
      );
    }
  }

}